package com.th.supcom.pds.drugsupply.client.widget;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.Loader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.dict.web.gwt.client.DictComboBox;
import com.th.supcom.framework.dict.web.gwt.client.model.DictModel;
import com.th.supcom.pds.common.client.commom.PdsAuditPrescServiceFactory;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.drugsupply.client.model.DrugInfoModel;
import com.th.supcom.pds.drugsupply.client.model.PdsPackageInfoModel;

/**
 * 药品属性信息表格
 * 
 * @author zli
 */
public class DrugSplitEditorGridPanel extends ContentPanel
{
    /** 公司版权信息. */
    public static final String copyright = "Copyright 2014, XuNuo Corporation";
    /** 每页分页数据条数. */
    private static final int s_LIMIT = Integer.MAX_VALUE;
    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";

    /** 定义选择模型. */
    private CheckBoxSelectionModel <PdsPackageInfoModel> m_chkModel;

    /** 定义储器. */
    private GroupingStore <PdsPackageInfoModel> m_drugMaintainStore;

    /** 操作按钮. */
    private DrugSplitPanelToolBar m_drugSplitPanelToolBar;

    /** 定义表. */
    private EditorGrid <PdsPackageInfoModel> m_grid;

    private String m_name;

    /** 定义分页加载器. */
    private BasePagingLoader <PagingLoadResult <PdsPackageInfoModel>> m_pagingLoad;

    public DrugSplitEditorGridPanel ()
    {
        init ();
        loadGridData ();
    }

    private void addListeners ()
    {
        m_grid.addListener (Events.BeforeEdit, new Listener <GridEvent <PdsPackageInfoModel>> ()
        {
            @Override
            public void handleEvent (final GridEvent <PdsPackageInfoModel> be)
            {

                final PdsPackageInfoModel pdsPackageInfoModel = be.getModel ();
                if (1 == be.getColIndex () && pdsPackageInfoModel.getEnable () == null)
                {
                    be.setCancelled (true);
                }
                if (pdsPackageInfoModel.getFlag () == null)
                {
                    return;
                }
                DrugSplitUtils.setUnedite (be, pdsPackageInfoModel, 7);
                DrugSplitUtils.setUnedite (be, pdsPackageInfoModel, 8);
            }
        });
    }

    private ColumnModel createGridHeader (final CheckBoxSelectionModel <PdsPackageInfoModel> chkModel)
    {
        final List <ColumnConfig> columns = new ArrayList <ColumnConfig> ();
        columns.add (chkModel.getColumn ());

        ColumnConfig column = new ColumnConfig ("phamName", "药品名称", 220);
        column.setEditor (getEditor ());
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ("phamStdCode", "药品编码", 100);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ("phamSpec", "药品规格", 150);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ("dosePerUnit", "最小单位剂量", 68);
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setRenderer (ClientUtils.getRenderer ("dosePerUnit"));
        column.setNumberFormat (NumberFormat.getFormat ("0.0000"));
        columns.add (column);

        column = new ColumnConfig ("doseUnitName", "剂量单位", 68);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ("phamUnitName", "基本单位", 68);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ("packageFactor", "分装规格", 80);
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setRenderer (DrugSplitUtils.generatorRenderForPackage ());
        formatPosIntEditor (column);
        columns.add (column);

        column = new ColumnConfig ("packageUnitName", "分包单位", 80);
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setRenderer (getRender ("packageUnitName"));
        column.setEditor (getEditorForUnit (new DictComboBox ("TJ0024")));
        columns.add (column);

        column = new ColumnConfig ("packagePrice", "分包价格", 80);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        return new ColumnModel (columns);
    }

    /**
     * 只能输入正整数的编辑器
     * 
     * @param column add by Zli
     */
    private void formatPosIntEditor (ColumnConfig column)
    {
        final NumberField numberField = new NumberField ();
        numberField.setRegex ("^[0-9]*[1-9][0-9]*$");
        numberField.setTitle ("请输入正整数");
        numberField.setFormat (NumberFormat.getFormat ("0"));
        column.setEditor (new CellEditor (numberField));
    }

    public CheckBoxSelectionModel <PdsPackageInfoModel> getChkModel ()
    {

        return m_chkModel;
    }

    public DrugSplitPanelToolBar getDrugSplitPanelToolBar ()
    {

        return m_drugSplitPanelToolBar;
    }

    private CellEditor getEditor ()
    {
        final DrugComboBoxForM check = new DrugComboBoxForM (new IExcuteQuery ()
        {

            @Override
            public void query (final PagingLoadConfig config, final String queryCondition, String deptcode, final AsyncCallback <PagingLoadResult <DrugInfoModel>> callback)
            {
                PdsAuditPrescServiceFactory.getPdsPropertyMaintainService ().getPhamBasicInfoListWithPagingByName (config, queryCondition, null, callback);
            }
        }, null);
        final CellEditor editor = new CellEditor (check)
        {

            @Override
            public Object postProcessValue (final Object value)
            {
                if (value == null)
                {
                    return null;
                }
                return check.getValue ().getPhamName ();
            }

            @Override
            public Object preProcessValue (final Object value)
            {
                if (value == null)
                {
                    return null;
                }
                return check.getValue ();
            }

        };
        check.setAllowBlank (false);
        check.addSelectionChangedListener (new SelectionChangedListener <DrugInfoModel> ()
        {

            @Override
            public void selectionChanged (final SelectionChangedEvent <DrugInfoModel> se)
            {
                if (se.getSelectedItem () == null)
                {
                    return;
                }
                m_chkModel.getSelectedItem ().setPhamStdCode (se.getSelectedItem ().getPhamStdCode ());
                m_chkModel.getSelectedItem ().setPhamSpec (se.getSelectedItem ().getPhamSpec ());
                m_chkModel.getSelectedItem ().setDoseUnitName (se.getSelectedItem ().getDoseUnitName ());
                m_chkModel.getSelectedItem ().setDosePerUnit (se.getSelectedItem ().getDosePerUnit ());
                m_chkModel.getSelectedItem ().setPhamUnitName (se.getSelectedItem ().getPhamUnitName ());
            }
        });
        return editor;
    }

    private CellEditor getEditorForUnit (final DictComboBox combo)
    {
        final CellEditor editor = new CellEditor (combo)
        {
            @Override
            public Object postProcessValue (final Object value)
            {
                if (value == null)
                {
                    return value;
                }
                m_grid.getStore ().getAt (super.row).setPackageUnit (combo.getValue ().getDictItemCode ());

                return combo.getValue ().getDictItemName ();
            }

            @Override
            public Object preProcessValue (final Object value)
            {
                if (value == null)
                {
                    return value;
                }
                DictModel dictModel = null;
                for (final DictModel dict : combo.getStore ().getModels ())
                {
                    if (dict.getDictItemName ().equals (value.toString ()))
                    {
                        dictModel = dict;
                        break;
                    }
                }
                combo.setEditable (false);

                return dictModel;

            }
        };

        return editor;
    }

    public ListStore <PdsPackageInfoModel> getListStore ()
    {
        return this.m_drugMaintainStore;
    }

    private GridCellRenderer <ModelData> getRender (final String name)
    {
        return new GridCellRenderer <ModelData> ()
        {

            @Override
            public Object render (final ModelData model, final String property, final ColumnData config, final int rowIndex, final int colIndex, final ListStore <ModelData> store,
                                  final Grid <ModelData> grid)
            {
                return DrugSplitUtils.strModelName (ClientUtils.avoidNull (model.get (name)), model);
            }
        };
    }

    private void init ()
    {
        // 初始化中心面板
        setHeaderVisible (false);
        setLayout (new FitLayout ());

        m_chkModel = new CheckBoxSelectionModel <PdsPackageInfoModel> ();
        m_chkModel.setSelectionMode (SelectionMode.SIMPLE);
        m_grid = this.initdrugMaintain ();
        addListeners ();
        m_grid.setView (DrugSplitUtils.createGroupingView ());
        m_drugSplitPanelToolBar = new DrugSplitPanelToolBar (m_chkModel);
        StoreFilterField <PdsPackageInfoModel> filter = DrugSplitUtils.createFilter ();
        filter.bind (m_grid.getStore ());
        m_drugSplitPanelToolBar.add (filter);
        add (m_grid);

        setTopComponent (m_drugSplitPanelToolBar);
    }

    private EditorGrid <PdsPackageInfoModel> initdrugMaintain ()
    {
        final EditorGrid <PdsPackageInfoModel> grid = new EditorGrid <PdsPackageInfoModel> (initStore (), createGridHeader (m_chkModel));
        grid.setColumnReordering (true);
        grid.setSelectionModel (m_chkModel);
        grid.addPlugin (m_chkModel);
        grid.setStyleAttribute ("border", "0px");
        grid.setColumnLines (true);
        return grid;
    }

    /**
     * 初始化分页加载器.
     * 
     */
    private void initPagingLoad (final RpcProxy <PagingLoadResult <PdsPackageInfoModel>> proxy)
    {
        m_pagingLoad = new BasePagingLoader <PagingLoadResult <PdsPackageInfoModel>> (proxy);
        m_pagingLoad.setRemoteSort (true);
    }

    private ListStore <PdsPackageInfoModel> initStore ()
    {
        final RpcProxy <PagingLoadResult <PdsPackageInfoModel>> proxy = new RpcProxy <PagingLoadResult <PdsPackageInfoModel>> ()
        {

            @Override
            protected void load (final Object loadConfig, final AsyncCallback <PagingLoadResult <PdsPackageInfoModel>> callback)
            {
                PdsAuditPrescServiceFactory.getPhamSplitInfoService ().getPackageInfoListWithPaging ((PagingLoadConfig) loadConfig, m_name, callback);

            }
        };
        this.initPagingLoad (proxy);
        m_drugMaintainStore = new GroupingStore <PdsPackageInfoModel> (m_pagingLoad);
        m_drugMaintainStore.groupBy ("vphamStdCode");
        return m_drugMaintainStore;

    }

    /**
     * 加载库存定义数据.
     */
    public final void loadGridData ()
    {

        m_name = m_drugSplitPanelToolBar.getPhamName ().getValue ();
        mask ("加载中");
        m_pagingLoad.load (0, DrugSplitEditorGridPanel.s_LIMIT);
        m_pagingLoad.addListener (Loader.Load, new Listener <BaseEvent> ()
        {
            @Override
            public void handleEvent (final BaseEvent be)
            {
                unmask ();
            }
        });
    }

    public EditorGrid <PdsPackageInfoModel> getGrid ()
    {

        return m_grid;
    }

}
